# -*- coding: UTF-8 -*-
import  pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df_titanic = pd.read_csv('train.csv')

#如果不知道函数名是什么，可以只敲击前几个记得的字母，按TAB键盘
df_titanic.isnull().sum() #统计空的个数
df_titanic.Age.fillna(0) #选一列进行空值填充
df_titanic.Age.median() #取中位数字
df_titanic.Age = df_titanic.Age.fillna(df_titanic.Age.median()) #,inplace=True
# print(df_titanic.Age)
df_titanic.Sex.value_counts()
#分析性别对生存的影响
Sur_sex = df_titanic[df_titanic.Survived ==1].Sex.value_counts()  #生还数据统计
Dead_sex  = df_titanic[df_titanic.Survived ==0].Sex.value_counts() #死亡数据统计
df_sex=pd.DataFrame([Sur_sex,Dead_sex],index=['Sur_sex','Dead_sex'])
df_sex =df_sex.T
df_sex['p_sur']=df_sex.Sur_sex / (df_sex.Sur_sex + df_sex.Dead_sex)
df_sex['p_dead' ]=df_sex.Dead_sex / (df_sex.Sur_sex + df_sex.Dead_sex)
# df_sex.plot.bar()  #绘图成功，但效果不理想
# df_sex[['p_sur','p_dead']].plot.bar(stacked =True)  #男女中生还者的比例情况
#性别对生还者，影响还是较大的


#分析年龄对生存的影响
Sur_age = df_titanic[df_titanic.Survived ==1].Age    #生还数据
Dead_age  = df_titanic[df_titanic.Survived ==0].Age   #死亡数据
df_age=pd.DataFrame([Sur_age,Dead_age],index=['Sur_age','Dead_age'])
df_age = df_age.T
# df_age.plot.hist(stacked=True,bins=30)  #直方图 bins 柱子多少 ，stacked重叠 ,但还不直观
# df_age.plot.kde(xlim=(0,80)) #密度图
# print(df_titanic.Age.describe())  #根据年龄分布，对密度图的年龄进行限制 xlim=(x,y)

#对年龄层次进行分析
age =16
young = df_titanic[df_titanic.Age <= age ]['Survived'].value_counts()
old = df_titanic[df_titanic.Age > age ]['Survived'].value_counts()
df =pd.DataFrame([ young, old] , index=['young','old'])
df =df.T
df.index=['dead','survived']
df['p_young'] = df.young / (df.young + df.old)
df['p_old'] = df.old / (df.young + df.old)
# df[['p_young','p_old']].plot.bar(stacked=True)  #年轻和年老的生还和死亡的占比

#分析票价，票价和年龄相似
Sur_fare = df_titanic[df_titanic.Survived ==1].Fare    #生还数据
Dead_fare  = df_titanic[df_titanic.Survived ==0].Fare   #死亡数据
df_fare=pd.DataFrame( [Sur_fare,Dead_fare] , index=['sur_fare','dead_fare'])
df_fare = df_fare.T
# df_fare.plot.kde(xlim=[0,513])

# 可以看出低票价死亡人数较多

#组合特征
#同时查看年龄和票价对生还率的影响？
# ax =plt.subplot()
# ages = df_titanic[df_titanic.Survived ==0 ].Age
# fares = df_titanic[df_titanic.Survived ==0 ].Fare
# # colors = np.random.rand(len(ages))
# plt.scatter(ages,fares , s=20,c='green',alpha=0.3,edgecolors='gray',linewidths=2)  #散点图
#
# ages = df_titanic[df_titanic.Survived ==1 ].Age
# fares = df_titanic[df_titanic.Survived ==1 ].Fare
# plt.scatter(ages,fares , s=20,c='red',alpha=0.3,edgecolors='gray',linewidths=2)  #散点图
# ax.set_xlabel('Age')
# ax.set_ylabel('Fare')

#名字分析

df_titanic['title']=df_titanic.Name.apply(lambda name:name.split(',')[1].split('.')[0].strip())  #截取称谓
print(df_titanic.title.value_counts())
# plt.show()
